var User = require('../models/user');
var express = require('express');
var router = express.Router();
var sess;

router.route('/user')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {
        
        var user = new User();      // create a new instance of the Bear model
        user.name = req.body.name; 
        user.password = req.body.password;
        user.type = req.body.type;
       // mg.date = new Date();
        // save the bear and check for errors
        user.save(function(err) {
            if (err)
                res.json({message: 'failed',success: false});
          //  req.session.user = user; //why session here is null
		    res.cookie("user",user);
        req.session.user = user;
            res.json({ message: 'user created!',success: true});
        });   
    })

    .get(function(req, res) {
      User.find(function(err, users) {
        if (err) {
         return res.send(err);
        }
        res.json(users);
      })
    });
router.route('/user/:name')
  .get(function(req,res){
    User.findOne({'name':req.params.name},function(err,user){
      if (err)
         res.json({success: false});
     console.log(req.session.user);
       res.json({message: user,success: true});
    });
});

router.route('/logout')
  .get(function(req,res){
     res.cookie("user",null);
     req.session.user = null;
     res.json({success: true});
})

module.exports = router;